package com.colin.controller;

import com.colin.pojo.Guest;
import com.colin.pojo.GuestList;
import com.colin.service.GuestServiceImpl;
import com.colin.utils.TimeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;

@Controller
@RequestMapping("/message")
public class MessageController {
    @Autowired
    private GuestServiceImpl guestServiceImpl;
    @RequestMapping("/index")
    public String index(String keyword , Model model , HttpSession session){
        HashMap<Object, Object> map = new HashMap<>();
        if (keyword != null){
            map.put("content" , "%" + keyword + "%");
        }
        System.out.println(map);
        List<GuestList> guests = guestServiceImpl.queryAllGuest(map);
        guests.forEach((e) -> {
            // 处理时间格式化
            e.setCreateTime(TimeUtils.formatTime(Integer.parseInt(e.getCreateTime())));
        });
        model.addAttribute("list" , guests);
        return "message/index";
    }

    @RequestMapping("/send")
    public String send(){
        return "message/send";
    }

    @PostMapping("/send")
    public String doSend(String content , Model model , HttpSession session){
        if (content.equals("")){
            model.addAttribute("error" , "请输入留言内容");
            return "message";
        }
        int uid = (int) session.getAttribute("userInfoId");
        Guest guest = new Guest(0 , content , uid , TimeUtils.getTime());
        int res = guestServiceImpl.addGuest(guest);
        if (res > 0){
            return "redirect:/message/index";
        }
        model.addAttribute("error" , "发布失败");
        return "message";
    }

    @RequestMapping("/{id}")
    public String detail(@PathVariable("id") int id , Model model){
        GuestList guest = guestServiceImpl.queryGuestById(id);
        model.addAttribute("content" , guest.getContent());
        model.addAttribute("create_time" , TimeUtils.formatTime(Integer.parseInt(guest.getCreateTime())));
        model.addAttribute("createUser" , guest.getUsername());
        return "message/detail";
    }
}
